/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.octopus.optiworks.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.octopus.optiworks.model.Product;
import com.octopus.optiworks.model.Template;
import com.octopus.optiworks.model.Employee;
import com.octopus.optiworks.service.StepService;
import com.octopus.optiworks.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Web MVC controller that handles operations related to managing users, such as editing them and deleting them. 
 */
@Controller
@RequestMapping("/template")
public class TemplateController {

	private TemplateValidator templateValidator = new TemplateValidator();

	@Autowired
    private UserService userService;
	
	@Autowired
    private StepService stepService;

    @RequestMapping("/manage.o")
    @RequiresPermissions("template:manage")
    public void manage(Model model) {
    	Employee user =  this.userService.getCurrentUser();
    	model.addAttribute("currentUser", user);
        model.addAttribute("templates", stepService.getAllTemplates());
    }

    @RequestMapping(value="/edit.o",method= RequestMethod.GET)
    @RequiresPermissions("template:edit")
    public String showEditTemplateForm(Model model, @RequestParam Long templateId, @ModelAttribute Template template) {
    	Employee cu =  this.userService.getCurrentUser();
    	model.addAttribute("currentUser", cu);
    	model.addAttribute("action", "Edit");
        Template r = stepService.getTemplate(templateId);
        template.setId(templateId);
        template.setName(r.getName());
        template.setDescription(r.getDescription());
        template.setSteps(r.getSteps());
        return "template/edit";
    }

    @RequestMapping(value="/edit.o",method= RequestMethod.POST)
    @RequiresPermissions("template:edit")
    public String editTemplate(Model model, @RequestParam Long templateId, @ModelAttribute Template template, BindingResult errors) {
    	templateValidator.validate(template, errors );
        if( errors.hasErrors() ) {
        	model.addAttribute("action", "Edit");
            return "template/edit";
        }
        template.setId(templateId);
        try{
        	stepService.updateTemplate(template);
        }catch (org.springframework.jdbc.UncategorizedSQLException e){
        	e.printStackTrace();
        	errors.rejectValue( "name", "error.name.exist", "The name has already existed." );
        	model.addAttribute("action", "Edit");
            return "template/edit";
        }
        return "redirect:/template/manage.o";
    }

    @RequestMapping("/delete.o")
    @RequiresPermissions("template:delete")
    public String deleteTemplate(Model model, @RequestParam Long templateId) {
        Assert.isTrue( templateId != 1, "Cannot delete default template" );
        try{
        	stepService.deleteTemplate( templateId );
        }catch(UncategorizedSQLException e){
        	model.addAttribute("error", "error.template.inuse");
        	this.manage(model);
        	return "template/manage";
        }catch(DataIntegrityViolationException e){
        	model.addAttribute("error", "error.template.inuse");
        	this.manage(model);
        	return "template/manage";
        }
        return "redirect:/template/manage.o";
    }
    
    @RequestMapping(value="/create.o",method= RequestMethod.GET)
    public String showCreateTemplateForm(Model model, @ModelAttribute Template template) {
    	Employee cu =  this.userService.getCurrentUser();
    	model.addAttribute("currentUser", cu);
    	model.addAttribute("action", "Create");
    	template.setScope("step10_1, step10_2, step20, step30_1, step30_2, step40, step50, step60, step70, step80, step90, " +
    			"step100_1, step100_2, step100_3, step110, step120_1, step120_2, step130, step140_1, step140_2, " +
    			"step150, step160, step170_1, step170_2, step180");
        return "template/edit";
    }

    @RequestMapping(value="/create.o",method= RequestMethod.POST)
    public String createTemplate(Model model, @ModelAttribute Template template, BindingResult errors) {
    	templateValidator.validate(template, errors );
        if( errors.hasErrors() ) {
        	model.addAttribute("action", "Create");
            return "template/edit";
        }
        try{
        	stepService.createTemplate(template);
        }catch (org.springframework.dao.DataIntegrityViolationException e){
        	e.printStackTrace();
        	errors.rejectValue( "name", "error.name.exist", "The name has already existed." );
        	model.addAttribute("action", "Create");
            return "template/edit";
        }
        return "redirect:/template/manage.o";
    }
    
	@RequestMapping(value = "/preview.o", method = RequestMethod.GET)
	public String view(Model model, @RequestParam Long templateId, HttpServletRequest request) throws Exception{
    	Employee user =  this.userService.getCurrentUser();
    	model.addAttribute("currentUser", user);
    	Template template = this.stepService.getTemplate(templateId);
    	InitProcessCommand init = new InitProcessCommand();
    	init.setNumber("1");
    	init.setTemplate(template);
		Product product = this.stepService.newProduct(init, true);
		request.setAttribute("product", product);
		model.addAttribute("View","View");
		String page = "template/preview";
		return page;
	}

}
